# -*- coding: utf-8 -*-

from flask import request, redirect, flash, render_template, url_for
from flask import Blueprint,make_response,session,Response
from app.exts import db
from app.models import TodoModel
from flask_login import login_user, login_required, logout_user, current_user
 
from flask import current_app # 就是实例化之后的APP对象,可以获取config中的参数

from . import todo_bp

# @todo_bp.url_value_preprocessor
# def get_profile_owner(endpoint, values):
#     query = User.query.filter_by(url_slug=values.pop('user_url_slug'))
#     g.profile_owner = query.first_or_404()
    


@todo_bp.route('/', methods=['GET', 'POST'])
def index():
    # print(current_app.config['DATA_DIR'])
    # print(current_app.url_map)
    # return '这是首页'
    
    todo = TodoModel.query.order_by('id')
    # _form = request.form

    # if request.method == 'POST':
    #     title = _form["title"]
    #     td = TodoModel(title=title)
    #     try:
    #         td.store_to_db()
    #         # flash("add task successfully!")
    #         return redirect(url_for('todo.index'))
    #     except Exception as e:
    #         print(f"-->{e}")
    #         # flash("fail to add task!")
    uid = session.get('username', None)
    print(f'uid------------3={uid}')
    return render_template('todo/index.html', user=uid, todo=todo)
 
@todo_bp.route('/<int:todo_id>/del')
def del_todo(todo_id):
    todo = TodoModel.query.filter_by(id=todo_id).first()
    if todo:
        todo.delete_todo()
    flash("delete task successfully")
    return redirect(url_for('todo.index'))


@todo_bp.route('/<int:todo_id>/edit', methods=['GET', 'POST'])
def edit(todo_id):
    todo = TodoModel.query.filter_by(id=todo_id).first()

    if request.method == 'POST':
        TodoModel.query.filter_by(
            id=todo_id
        ).update({
            TodoModel.title: request.form['title']
        })
        db.session.commit()
        flash("update successfully!")
        return redirect(url_for('todo.index'))

    return render_template('todo/edit.html', todo=todo)


@todo_bp.route('/<int:todo_id>/done')
def done(todo_id):
    todo = TodoModel.query.filter_by(id=todo_id).first()
    if todo:
        TodoModel.query.filter_by(id=todo_id).update({TodoModel.status: True})
        db.session.commit()
        flash("task is completed!")

    return redirect(url_for('todo.index'))


@todo_bp.route('/<int:todo_id>/redo')
def redo(todo_id):
    todo = TodoModel.query.filter_by(id=todo_id).first()
    if todo:
        TodoModel.query.filter_by(id=todo_id).update({TodoModel.status: False})
        flash("redo successfully!")
        db.session.commit()

    return redirect(url_for('todo.index'))

# 以下是测试的路由试图函数
@todo_bp.route('/login', methods=['GET', 'POST'])
def login():
   if 'user' in session:
       return '已经登录'
   else:
       return '未登录'


# 异常函数捕获
class InvalidUsage(Exception):
    status_code = 400
 
    def __init__(self, message, status_code=400):
        Exception.__init__(self)
        self.message = message
        self.status_code = status_code

@todo_bp.errorhandler(InvalidUsage)
def invalid_usage(error):
    response = make_response(error.message)
    response.status_code = error.status_code
    return response


@todo_bp.route('/exception')
def exception():
    raise InvalidUsage('No privilege to access the resource', status_code=403)


@todo_bp.route('/large.csv')
def generate_large_csv():
    def generate():
        for row in range(50000):
            line = []
            for col in range(500):
                line.append(str(col))
            if row % 1000 == 0:
                print('row: %d' % row)
            yield ','.join(line) + '\n'

    return Response(generate(), mimetype='text/csv')